﻿using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace WCrawlerLib
{
    public class BrowserSession_phpBB3 : BrowserSession_phpBB
    {
        public BrowserSession_phpBB3()
        {
            ForumTypeId = enumForumType.phpBB3;
        }

        /// <summary>
        /// Get PostId
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public override string[] GetThreadPostNum(HtmlDocument doc)//(string threadUrl)
        {
            //HtmlDocument doc = Get(threadUrl);
            string[] result = new string[2];

            if (doc != null)
            {
                //Find thread num
                ///posting.php?mode=reply&f=42&t=547301
                string xPath = ".//a[contains(@href,'posting.php?mode=reply')]";
                HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(xPath);
                if (nodeCollection != null)
                {
                    string replyUrl = nodeCollection[0].Attributes["href"].Value.Replace("postcount", "");
                    Regex r = new Regex(@"posting\.php\?mode\=reply(\&|\&amp\;)f=[0-9]+(\&|\&amp\;)t=(?<threadnum>[0-9]+)");
                    Match m = r.Match(replyUrl);
                    if (m.Success)
                    {
                        result[0] = m.Result("${threadnum}");
                    }
                }

                //Find first post num
                xPath = ".//div[starts-with(@id,'p') and substring-after(@id, 'p') >= 0]";
                nodeCollection = doc.DocumentNode.SelectNodes(xPath);
                if (nodeCollection != null)
                    result[1] = nodeCollection[0].Attributes["id"].Value.Replace("p", "");
            }
            return result;
        }

        /// <summary>
        /// Update content of a thread have been posted. 
        /// After that reply a message to alert updated content 
        /// </summary>
        /// <param name="forumUrl"></param>
        /// <param name="topicUrl"></param>
        /// <param name="editParams"></param>
        /// <param name="message"></param>
        /// <param name="updateReason"></param>
        /// <returns></returns>
        public override bool EditPost(string forumUrl, string topicUrl, string postId, string editParams, string subject, string message, string updateReason, string icon)
        {
            bool result = false;
            //open topicurl to get postid
            Get(forumUrl + "/" + topicUrl);

            //Load edit page
            string xPath = ".//div[starts-with(@id,'p') and substring-after(@id, 'p') >= 0]//a[@class='controlbutton cb-edit']";
            string editUrl = HtmlDoc.DocumentNode.SelectNodes(xPath)[0].Attributes["href"].Value;
            Get(editUrl);

            //init post params
            //_postParams = InitPostUpdateParams(editParams, subject, message + "\n" + updateReason, icon);
            _postParams = InitPostParams(enumPost.EditPost, editParams, subject, message + "\n" + updateReason, icon);
            
            //start update
            xPath = ".//form[@id='postform' and @method='post']";
            string postUrl = HtmlDoc.DocumentNode.SelectNodes(xPath)[0].Attributes["action"].Value;
            Post(postUrl);
            if (HtmlWeb.StatusCode == HttpStatusCode.OK)
                result = true;
            return result;
        }

        public DataRow FillDataRow(string forumUrl, HtmlNode node, DataTable table)
        {
            DataRow row = table.NewRow();

            string xPath = ".//a[@class='topictitle']";
            HtmlNodeCollection nodeCollect1 = node.SelectNodes(xPath);
            string href = nodeCollect1[0].Attributes["href"].Value;

            //1. Get thread num
            //Regex r = new Regex("t(?<threadnum>[0-9]+)");
            //Match m = r.Match(href);
            //row["ThreadNum"] = m.Result("${threadnum}");

            ////2. Get post num
            //row["PostNum"] = GetPostNum(href);

            //3. Get title & url
            row["Title"] = nodeCollect1[0].InnerHtml;
            row["Url"] = href.Replace(forumUrl + "/", "");

            //4. Get Replies
            xPath = ".//dd[@class='posts' and ./text() !='']";
            nodeCollect1 = node.SelectNodes(xPath);
            Regex r = new Regex("[0-9]+");
            Match m = r.Match(nodeCollect1[0].InnerText);
            row["Replies"] = m.Value;

            //5. Get views
            xPath = ".//dd[@class='views' and ./text() !='']";
            nodeCollect1 = node.SelectNodes(xPath);
            m = r.Match(nodeCollect1[0].InnerText);
            row["Views"] = m.Value;

            //6. Get Forum
            xPath = ".//a[3]";
            nodeCollect1 = node.SelectNodes(xPath);
            href = nodeCollect1[0].Attributes["href"].Value;
            row["Forum"] = nodeCollect1[0].OuterHtml;

            return row;
        }

       
        /// <summary>
        /// Search threads with paging
        /// </summary>
        /// <param name="forumUrl"></param>
        /// <param name="doc"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public override List<DataRow> SearchThreadsByPaging(string forumUrl, HtmlDocument doc, DataTable table)
        {
            List<DataRow> rowList = new List<DataRow>();
            string xPath = @".//li[starts-with(@class,'row bg')]";
            HtmlNodeCollection nodeCollection = HtmlDoc.DocumentNode.SelectNodes(xPath);
            if (nodeCollection != null)
            {
                foreach (HtmlNode node in nodeCollection)
                {
                    DataRow row = FillDataRow(forumUrl, node, table);
                    rowList.Add(row);
                }
            }
            return rowList;
        }
    }
}